﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DiemTichLuyModels.Context;
using DiemTichLuyModels.Object;
using System.Data;
namespace DiemTichLuy.Controllers
{
    public class SanPhamController : Controller
    {
        //
        // GET: /SanPham/
        private DataContext db = new DataContext();
        public ActionResult Index()
        {
            Session["abc"] = "a";
            var producst = db.SanPham;
            return View(producst);
        }
        public ActionResult ThemSanPham()
        {
            ViewBag.LoaiSanPham = new SelectList(db.LoaiSanPhams, "ID", "TenLoai");
            return View();
        }
        [HttpPost]
        public ActionResult ThemSanPham(DiemTichLuyModels.Object.SanPham model)
        {
            if (ModelState.IsValid)
            {
                db.SanPham.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index","SanPham");
            }
            ViewBag.LoaiSanPham = new SelectList(db.LoaiSanPhams, "ID", "TenLoai");
            return View();
        }
        public ActionResult XoaSanPham(int SanPhamID)
        {
            var sanpham = db.SanPham.Where(m => m.ID == SanPhamID).FirstOrDefault();
            if (sanpham == null)
            {
                return RedirectToAction("Index", "SanPham");
            }
            db.SanPham.Remove(sanpham);
            db.SaveChanges();
            return RedirectToAction("Index", "SanPham");
        }
        public ActionResult SuaSanPham(int SanPhamID, string TenSapham)
        {
            var sanpham = db.SanPham.Where(m => m.ID == SanPhamID).FirstOrDefault();
            if (sanpham == null)
            {
                return RedirectToAction("Index", "SanPham");
            }
            ViewBag.LoaiSanPham = new SelectList(db.LoaiSanPhams, "ID", "TenLoai",sanpham.LoaiSanPhamID);
            return View(sanpham);
        }
        [HttpPost]
        public ActionResult SuaSanPham(DiemTichLuyModels.Object.SanPham model, int giasanpham)
        {
            if (ModelState.IsValid)
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "SanPham");
            }
            ViewBag.LoaiSanPham = new SelectList(db.LoaiSanPhams, "ID", "TenLoai", model.LoaiSanPhamID);
            return View(model);
        }
    }
}
